from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import asyncio
from contextlib import asynccontextmanager
from pydantic import BaseModel
from typing import Dict, List, Any
import logging
import time

from services.patent_search_service import PatentSearchService
from services.patent_analysis_service import PatentAnalysisService
from services.table_generation_service import TableGenerationService

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

@asynccontextmanager
async def lifespan(app: FastAPI):
    global search_service, analysis_service, table_service
    logger.info("初始化服务...")
    
    search_service = PatentSearchService()
    analysis_service = PatentAnalysisService()
    table_service = TableGenerationService()
    
    logger.info("服务初始化完成")
    yield

app = FastAPI(title="Patent Analysis API", version="1.0.0", lifespan=lifespan)

# 配置CORS
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 请求模型
class DemandRequest(BaseModel):
    demand_text: str
    top_n: int = 1000

# 全局服务实例
search_service = None
analysis_service = None
table_service = None

@app.post("/api/search-patents")
async def search_patents(request: DemandRequest):
    """搜索专利并返回基础信息"""
    try:
        patents = search_service.search_demand_patents(request.demand_text, request.top_n)
        return {"patents": patents, "count": len(patents)}
    except Exception as e:
        logger.error(f"专利搜索错误: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/analyze-inventors")
async def analyze_inventors(request: DemandRequest):
    """分析发明人信息"""
    try:
        # 先搜索专利
        patents = search_service.search_demand_patents(request.demand_text, request.top_n)
        # 分析发明人
        inventors_info = await analysis_service.analyze_inventors(patents)
        return {"inventors_info": inventors_info}
    except Exception as e:
        logger.error(f"发明人分析错误: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/generate-table1")
async def generate_table1(request: DemandRequest):
    """生成表1: Topic数据表"""
    try:
        patents = search_service.search_demand_patents(request.demand_text, request.top_n)
        table1 = await table_service.generate_table1(patents, request.demand_text)
        return {"table1": table1}
    except Exception as e:
        logger.error(f"表1生成错误: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/generate-table2")
async def generate_table2(request: DemandRequest):
    """生成表2: All数据表"""
    try:
        patents = search_service.search_demand_patents(request.demand_text, request.top_n)
        table2 = await table_service.generate_table2(patents)
        return {"table2": table2}
    except Exception as e:
        logger.error(f"表2生成错误: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@app.post("/api/generate-table3")
async def generate_table3(request: DemandRequest):
    """生成表3: Topic/All比例数据表"""
    try:
        patents = search_service.search_demand_patents(request.demand_text, request.top_n)
        table1 = await table_service.generate_table1(patents, request.demand_text)
        table2 = await table_service.generate_table2(patents)
        table3 = await table_service.generate_table3(table1, table2)
        return {"table3": table3}
    except Exception as e:
        logger.error(f"表3生成错误: {e}")
        raise HTTPException(status_code=500, detail=str(e))
    

@app.post("/api/full-analysis")
async def full_analysis(request: DemandRequest):
    """
    综合分析接口：
    - 分析发明人信息
    - 生成表1（Topic数据表）
    - 生成表2（All数据表）
    - 生成表3（Topic/All比例数据表）
    """
    try:
        start = time.time()

        # 统一获取专利数据
        patents = search_service.search_demand_patents(request.demand_text, request.top_n)

        # 并行执行分析任务（推荐使用 asyncio.gather 提升效率）
        inventors_info_task = analysis_service.analyze_inventors(patents)
        table1_task = table_service.generate_table1(patents, request.demand_text)
        table2_task = table_service.generate_table2(patents)

        inventors_info, table1, table2 = await asyncio.gather(
            inventors_info_task, table1_task, table2_task
        )

        # 表3依赖表1和表2
        table3 = await table_service.generate_table3(table1, table2)
        end = time.time()
        logger.info(f"综合分析完成，耗时: {end - start:.2f} 秒")

        return {
            "inventors_info": inventors_info,
            "table1": table1,
            "table2": table2,
            "table3": table3
        }

    except Exception as e:
        logger.error(f"综合分析错误: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@app.get("/api/health")
async def health_check():
    """健康检查"""
    return {"status": "ok", "message": "Patent Analysis API is running"}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
